package servlet;

import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.connector.Request;

import service.UserService;
import dao.UserDao;

public class LoginServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	
	public LoginServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		doPost(request,response);
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("gbk");
		String username,password;
		UserService us =new UserService();
		HttpSession ss = request.getSession();
		
		try{
			username = request.getParameter("username");
			password = request.getParameter("password");
			String b = us.login(username, password);
			if(b!=null){
				ss.setAttribute("id", b);
				
				request.getRequestDispatcher("../inform.jsp").forward(request, response);
			}
			else{
				PrintWriter out = response.getWriter();
				//out.println("<%@ page language="java" import='java.util.*' pageEncoding='utf-8' %> ");
				out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
				out.println("<HTML>");
				out.println("  <HEAD><TITLE>登录失败</TITLE></HEAD>");
				out.println("  <BODY>");
	            out.println("<h1>帐号或用户名错误!</h1>");
	            out.println(" <a href='../login.jsp'>点击返回</a>");
				out.println("  </BODY>");
				out.println("</HTML>");
				out.flush();
				out.close();
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
}
